import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {PickerController, NavController, ModalController, AlertController} from '@ionic/angular';
import {HttpService} from 'src/app/service/http.service';
import {ImagePicker} from '@ionic-native/image-picker/ngx';
import {TransferService} from 'src/app/service/transfer.service';
import {ToastService} from '../../../service/toast.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-doctor-person-edit',
    templateUrl: './doctor-person-edit.page.html',
    styleUrls: ['./doctor-person-edit.page.scss'],
})
export class DoctorPersonEditPage implements OnInit {
    userType = 2;
    aType = '';
    aValue = '';
    secondValue = '';
    sexBox = [{code: 1, value: '男'}, {code: 2, value: '女'}];
    payBox = [{code: 1, value: '直接预约'}, {code: 2, value: '代理预约'}];
    personName = '';
    personSex = '';
    personCollege = '';
    departmentName = '';
    regionName = '';
    defaultColumnOptions = [];
    hospitalBox = [];
    aBox = [];
    verifyCode: any = {
        verifyCodeTips: 'GetCode',
        countdown: 300,
        disable: true,
    };
    emailCode = '';
    newEmail = '';
    sysLang = '';

    // tslint:disable-next-line: max-line-length
    constructor(
        private nav: NavController,
        private activatedRoute: ActivatedRoute,
        private pickercontroller: PickerController,
        private httpService: HttpService,
        private toastSrv: ToastService,
        private modalController: ModalController,
        private alertController: AlertController,
        private imagePicker: ImagePicker,
        private transferSrv: TransferService,
        private translate: TranslateService,
    ) {
        activatedRoute.queryParams.subscribe(queryParams => {
            if (!!queryParams.dataType) {
                this.aType = queryParams.dataType;
            }
            if (!!queryParams.value) {
                this.aValue = queryParams.value;
            }
            if (!!queryParams.secondValue) {
                this.secondValue = queryParams.secondValue;
            }
            if (!!queryParams.userType) {
                this.userType = Number(queryParams.userType);
            }
        });
    }

    ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
        if (this.aType === 'region') {

        } else if (this.aType === 'department') {
            this.getDepartments();
        } else if (this.aType === 'CH') {
            this.getHospital();
        }
    }

    public sexSelect() {
        // console.log(this.aValue);
    }

    public paySelect() {
        // console.log(this.aValue);
    }

    public savePatient() {
        const self = this;
        if (this.aType === 'name') {
            this.saveData('nickname', self.aValue);
        } else if (this.aType === 'sex') {
            this.saveData('gender', self.aValue);
        } else if (this.aType === 'college') {
            this.saveData('university', self.aValue);
        } else if (this.aType === 'MQ') {
            this.saveData('medical_qualification', self.secondValue);
        } else if (this.aType === 'PH') {
            this.saveData('personal_honor', self.aValue);
        } else if (this.aType === 'PD') {
            this.saveData('personal_desc', self.aValue);
        } else if (this.aType === 'TP') {
            this.saveData('testing_item', self.aValue);
        } else if (this.aType === 'TestingCost') {
            this.saveData('order_price', self.aValue);
        } else if (this.aType === 'PN') {
            this.saveData('phone', self.aValue);
        } else if (this.aType === 'skype') {
            this.saveData('skype', self.aValue);
        } else if (this.aType === 'DA') {
            this.saveData('address', self.aValue);
        } else if (this.aType === 'RM') {
            this.saveData('order_type', self.aValue);
        } else if (this.aType === 'CH') {
            for (const aItem of this.aValue) {
                for (const bItem of this.hospitalBox) {
                    if (aItem === bItem.hospital_name) {
                        this.aBox.push(bItem.id);
                    }
                }
            }
            this.nav.pop();
        } else if (this.aType === 'email') {
            this.changeEmail();
        }
    }

    public async openPicker(numColumns = 1, numOptions = 5, multiColumnOptions) {
        const picker = await this.pickercontroller.create({
            columns: this.getColumns(numColumns, numOptions, multiColumnOptions),
            buttons: [
                {
                    text: 'Cancel',
                    role: 'cancel'
                },
                {
                    text: 'Confirm',
                    handler: (value) => {
                        this.departmentName = value['col-0'].text;
                        this.aValue = value['col-0'].value;
                    }
                }
            ]
        });
        await picker.present();
    }

    private getColumns(numColumns, numOptions, columnOptions) {
        const columns = [];
        for (let i = 0; i < numColumns; i++) {
            columns.push({
                name: `col-${i}`,
                options: this.getColumnOptions(i, numOptions, columnOptions)
            });
        }
        return columns;
    }

    private getColumnOptions(columnIndex, numOptions, columnOptions) {
        const options = [];
        for (let i = 0; i < numOptions; i++) {
            options.push({
                text: columnOptions[columnIndex][i % numOptions].name,
                value: i
            });
        }
        return options;
    }

    private async getDepartments() {
        const result: any = await this.httpService.get().setPath('/pub/source/departmentList').request();
        this.defaultColumnOptions[0] = result.data;
    }

    public async getHospital() {
        const result: any = await this.httpService.get()
            .setPath('/pub/source/hospitalList')
            .setQuery({
                cityRegionId: 9
            })
            .request();
        this.hospitalBox = result.data.rows;
    }

    public async getCode() {
        const result: any = await this.httpService.post()
            .setPath('/pub/user/verifyCode')
            .setBody({
                smsType: 3,
                type: 2,
                email: this.aValue,
            })
            .request();
        if (result.status === 0) {
            if (this.sysLang === 'en-us') {
                const aWord = 'Message Sent';
                this.toastSrv.setDuration(5000).showToast(aWord);
            } else {
                const aWord = '验证码已发送';
                this.toastSrv.setDuration(5000).showToast(aWord);
            }
            if (result.data.expire < 300) {
            } else {
                this.verifyCode.disable = false;
                this.settime();
            }
        }
    }

    public settime() {
        if (this.verifyCode.countdown === 1) {
            this.verifyCode.countdown = 300;
            this.verifyCode.verifyCodeTips = 'GetCode';
            this.verifyCode.disable = true;
            return;
        } else {
            this.verifyCode.countdown--;
        }

        this.verifyCode.verifyCodeTips = (this.sysLang === 'en-us' ? 'Resend(' : '重新获取(') + this.verifyCode.countdown + ')';
        setTimeout(() => {
            this.verifyCode.verifyCodeTips = (this.sysLang === 'en-us' ? 'Resend(' : '重新获取(') + this.verifyCode.countdown + ')';
            this.settime();
        }, 1000);
    }

    public async changeEmail() {
        if (this.sysLang === 'en-us') {
            if (!this.aValue) {
                this.toastSrv.showToast('Please Enter Exact Email');
                return;
            }
            if (!this.emailCode) {
                this.toastSrv.showToast('PLease Enter Verification Code');
                return;
            }
            if (!this.newEmail) {
                this.toastSrv.showToast('Please Enter New Email');
                return;
            } else {
                if (this.aValue === this.newEmail) {
                    this.toastSrv.showToast('Please Enter A New Email Different With Current');
                    return;
                }
            }
        } else {
            if (!this.aValue) {
                this.toastSrv.showToast('请输入正确的邮箱号码');
                return;
            }
            if (!this.emailCode) {
                this.toastSrv.showToast('请输入邮箱验证码');
                return;
            }
            if (!this.newEmail) {
                this.toastSrv.showToast('请输入新邮箱号');
                return;
            } else {
                if (this.aValue === this.newEmail) {
                    this.toastSrv.showToast('请输入与当前邮箱号不同的邮箱号');
                    return;
                }
            }
        }
        const result: any = await this.httpService.put()
            .setPath('/user/modifyIdentity/' + this.userType)
            .setBody({
                original: this.aValue,
                current: this.newEmail,
                verifyCode: this.emailCode
            })
            .request();
        if (result.status === 0) {
            const alert = await this.alertController.create({
                message: 'Modify Success',
                buttons: [
                    {
                        text: 'Confirm',
                        handler: () => {
                            this.nav.pop();
                        }
                    }
                ]
            });
            await alert.present();
        }
    }

    public async saveData(aKey, aParam) {
        const postBody: any = {};
        postBody[aKey] = aParam;
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.put()
            .setPath('/user/doctorUpdate/' + aUserId)
            .setBody({
                ...postBody
            })
            .request();
        if (result.status === 0) {
            const alert = await this.alertController.create({
                message: 'Modify Success',
                buttons: [
                    {
                        text: 'Confirm',
                        handler: () => {
                            this.nav.pop();
                        }
                    }
                ]
            });
            await alert.present();
        }
    }

    public async uploadImg() {
        const aUserId = localStorage.getItem('userId');
        try {
            const result = await this.imagePicker.getPictures({maximumImagesCount: 1});
            const uploadResult = await this.transferSrv.setPath('/upload/file')
                .setFile(result)
                .parseFile()
                .setFieldName('user')
                .setParams({
                    uploadType: 'attach',
                    userId: aUserId
                })
                .upload();
            if (uploadResult.status === 0) {
                this.aValue = uploadResult.data.resUrl;
            }
        } catch (e) {
            if (HttpService.EnvIndex < 2) {
                alert(JSON.stringify(e));
            }
        }
    }
}
